/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.test.impl;

import lombok.SneakyThrows;
import lombok.var;
import org.junit.Assert;
import org.springframework.core.io.ClassPathResource;

import java.io.*;

import static io.iec.edp.caf.rpc.test.impl.ConstVirable.*;

public class RpcTestImpl implements RpcTest {
    @Override
    public void testNoReturnRpc(String name) {
        Assert.assertTrue(name.equalsIgnoreCase(RPC_PARAM_NAME));
    }

    @Override
    public String testReturnRpc(String name) {
        Assert.assertTrue(name.equalsIgnoreCase(RPC_PARAM_NAME));
        return RPC_RETURN_STRING_VALUE;
    }

    @Override
    public String testReturnWithCustomeSerializeRpc(String name) {
        Assert.assertTrue(name.equalsIgnoreCase(RPC_PARAM_NAME));
        return RPC_RETURN_STRING_VALUE;
    }

    @SneakyThrows
    @Override
    public InputStream testDownloadFile() {
        File file = new ClassPathResource("上传下载测试.docx").getFile();
        if(file.exists()){
            FileInputStream stream = new FileInputStream(file);
            return stream;
        }else{
            return null;
        }
    }

    @SneakyThrows
    @Override
    public void testUploadFile(InputStream fileStream) {
        String currentDir = System.getProperty("user.dir");
        var outputStream = new FileOutputStream(currentDir);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fileStream.read(buffer)) != -1){
            outputStream.write(buffer,0, length);
        }

        File file = new File(currentDir);
        if(file.exists()){
            FileInputStream stream = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            String result = stringBuilder.toString();
            Assert.assertTrue(result.equalsIgnoreCase(RPC_FILE_CONTENT));
        }else{
            Assert.fail("文件上传失败");
        }
    }
}
